from DrissionPage import ChromiumPage, ChromiumOptions
import os
import re
import json
import time
import random
from DrissionPage.errors import ContextLostError

from chat_dify_blocking import get_text
import pyautogui
from clean_json_1 import process_json_1
from clean_json_2 import process_json_2

co = ChromiumOptions().set_paths(browser_path=r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe") # 设置浏览器路径
co.set_argument('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.2365.52')  # 设置 User-Agent
page = ChromiumPage(co)

# 拿到所有商品链接和商品名称
page.get('https://www.walmart.com/browse/patio-furniture/5428_91416?povid=HDL_PatioGarden_5428_POVcards_Outdoorupgrades_Patiofurniture_DSK_Jan_21&seo=patio-furniture&seo=5428_91416&page=8&affinityOverride=default')


all_goods = []

# 鼠标右键左滑
def mouse_right():
    # 获取屏幕中心坐标
    screen_width, screen_height = pyautogui.size()
    start_x, start_y = screen_width // 2, screen_height // 2
    end_x = start_x - 100  # 目标点（向左 100 像素）

    # 移动鼠标到屏幕中心
    pyautogui.moveTo(start_x, start_y, duration=0.5)

    # 按住鼠标右键
    pyautogui.mouseDown(button='right')

    # 生成滑动轨迹（曲线/随机波动）
    steps = random.randint(5, 10)  # 随机步数，增加不规律性
    for i in range(steps):
        # 计算当前位置
        curr_x = start_x - ((i + 1) / steps) * 100  # 逐步向左移动
        curr_y = start_y + random.randint(-3, 3)  # Y 方向增加随机抖动
        pyautogui.moveTo(curr_x, curr_y, duration=random.uniform(0.05, 0.15))

    # 释放鼠标右键
    pyautogui.mouseUp(button='right')

links = page.eles('x://div[@class="mb0 ph0-xl pt0-xl bb b--near-white w-25 pb3-m ph1"]')

i = 0

num = 705  # 初始文件编号

while True:
    page.wait(1)
    linkss = page.eles('x://div[@class="mb0 ph0-xl pt0-xl bb b--near-white w-25 pb3-m ph1"]')
    # print(f"linkss:{len(linkss)}")

    if i >= len(linkss):
        next_page = page.ele('x://i[@class="ld ld-ChevronRight pv1 primary"]')
        if next_page:
            next_page.click()
            page.wait(2)  # 增加等待时间，确保新页面加载完成
            i = 0  # 重置索引
            continue  # 重新获取 linkss
        else:
            print("没有下一页了")
            json_file_path = os.path.join(r"D:\subtitle\goods", f'walmart_goods_{num}.json')
            with open(json_file_path, 'w', encoding='utf-8') as f:
                json.dump(all_goods, f, ensure_ascii=False, indent=4)

            # **清洗数据**
            process_json_1(num)
            process_json_2(num)
            break

    # print(f"i:{i}")
    try:
        link = linkss[i]  # 这里可能报错
    except IndexError:
        print(f"索引 {i} 超出范围，linkss 长度为 {len(linkss)}，跳过...")
        break  # 防止无限循环

    i += 1
    for x in range(3):
        try:
            name = link.ele('x://span[@class="w_iUH7"]')
            if name:
                break
        except ContextLostError:
            print("商品名 等待重新加载...")
            time.sleep(1)  # 休息1秒再试

    goods_name = name.text
    # print(f"goods_name:{goods_name}")

    # 获取商品详情
    success = False
    for y in range(3):
        try:
            info = link.ele('x://a[@class="w-100 h-100 z-1 hide-sibling-opacity  absolute"]')
            if info:
                success = True
                break
        except ContextLostError:
            print("详情，等待重新加载...")
            time.sleep(1)

    if success:
        page.run_js('arguments[0].click();', info)
        page.wait(5)


        # 获取所有 li 元素
        for z in range(3):
            try:
                # lis = page.eles('x://div[@class="expand-collapse-content dangerous-html w_YUC7"]//li')
                lis = page.eles('x://div[@class="w_aoqv w_wRee w_fdPt"]')
                print(f"lis：{lis}")
                if lis:
                    break
            except ContextLostError:
                lis = None
                print("描述，等待重新加载...")
                time.sleep(1)

        if lis is None:
            print("未找到描述信息，跳过此商品")
            # mouse_right()
            # 关闭当前标签页

            continue

        # 提取文本内容
        li_texts = [li.text for li in lis]
        texts_all = li_texts[:5] if len(li_texts) > 5 else li_texts

        #关闭当前标签页
        # page.run_js('window.close()')
        pyautogui.hotkey('ctrl', 'w')  # 关闭当前标签页
        # mouse_right()
        print('返回上一页')
        print(f'texts_all{texts_all}')

        if texts_all:
            target_text = get_text('Use short sentences to summarize the selling points, target groups, and usage scenarios from this paragraph', texts_all)
            input = re.sub(r"\*\*Selling Points:\*\s*", "[Selling points]: ", target_text)
            input = re.sub(r"\*\*Target Groups:\*\s*", "[Target groups]: ", input)
            input = re.sub(r"\*\*Usage Scenarios:\*\s*", "[Usage scenarios]: ", input)
            input = re.sub(r"[\n-]+", " ", input).replace("\\n", "").replace("\\", "")

            out_put = get_text('Generate a sales script for this product targeting a US audience of up to 400 words [product]:', goods_name)
            out_put = out_put.replace("\n", "").replace("\\n", "").replace("\\", "")

            goods_dict = {
                'instruction': f'Generate a sales script for [{goods_name}] targeting American audiences',
                'input': input,
                'output': out_put
            }
            all_goods.append(goods_dict)

            # **当数据量达到 10，保存并清理**
            if len(all_goods) >= 10:
                json_file_path = os.path.join(r"D:\subtitle\goods", f'walmart_goods_{num}.json')
                with open(json_file_path, 'w', encoding='utf-8') as f:
                    json.dump(all_goods, f, ensure_ascii=False, indent=4)

                # **清洗数据**
                process_json_1(num)
                process_json_2(num)

                # **清空数据列表，并递增文件编号**
                all_goods.clear()
                num += 1

            page.wait(5)
            print(goods_dict)
    else:
        print("没有找到匹配的文本")
